package com.kinyx.framework.business;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import com.kinyx.framework.annotation.assist.CanNotNull;
import com.kinyx.framework.annotation.assist.ReturnNotNull;
import com.kinyx.framework.annotation.assist.Throws;
import com.kinyx.framework.bean.GetArgs;
import com.kinyx.framework.exception.KRuntimeException;
import com.kinyx.framework.file.KReader;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;

/**
 * 连接工具类
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class KURLConnection {

	/**
	 * GET请求
	 * @param args 请求参数
	 * @return 响应结果
	 */
	@ReturnNotNull
	@Throws(at = "KReader.read(InputStream, String)", value = "UnsupportedEncodingException", when = "new InputStreamReader(InputStream, String)")
	@Throws(at = "KReader.read(InputStream, String)", value = "IOException", when = "InputStreamReader.read()")
	@Throws(at = "KURLConnection.GET(GetArgs)", value = "MalformedURLException", when = "new URL(String)")
	@Throws(at = "KURLConnection.GET(GetArgs)", value = "IOException", when = "URLConnection.openConnection()")
	@Throws(at = "KURLConnection.GET(GetArgs)", value = "IOException", when = "URLConnection.connect()")
	@Throws(at = "KURLConnection.GET(GetArgs)", value = "IOException", when = "InputStream.getInputStream()")
	public static String GET(@CanNotNull final GetArgs args) {
		// 带参数的地址
		final String urlStr = args.getUrlWithParams();

		// 转换为URL对象
		URL url;
		try {
			url = new URL(urlStr);
		} catch (final MalformedURLException e) {
			throw new KRuntimeException(e);
		}

		// 打开连接
		URLConnection connection;
		try {
			connection = url.openConnection();
		} catch (final IOException e) {
			throw new KRuntimeException(e);
		}

		// 设置请求头
		if (args.getHeaders() != null) {
			args.getHeaders().forEach((key, value) -> { connection.setRequestProperty(key, value); });
		}

		// 设置代理
		if (args.getUserAgent() != null) {
			connection.addRequestProperty("User-Agent", args.getUserAgent());
		}

		// 连接请求
		try {
			connection.connect();
		} catch (final IOException e) {
			throw new KRuntimeException(e);
		}

		// 读取流
		InputStream is;
		try {
			is = connection.getInputStream();
		} catch (final IOException e) {
			throw new KRuntimeException(e);
		}
		return KReader.read(is, args.getCharset());
	}

}
